import 'package:get/get.dart';
import 'package:raze/lore/glyph/eco_education_essence.dart';

/// 环保教育状态管理
/// 全局环保教育内容状态，提供查询等功能
class EcoEducationChronicle extends GetxController {
  // 所有环保教育内容列表
  final _educationList = <EcoEducationEssence>[].obs;

  /// 获取所有环保教育内容列表
  List<EcoEducationEssence> get educationList => _educationList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultEducations();
  }

  /// 初始化默认环保教育数据
  void _initializeDefaultEducations() {
    _educationList.value = [
      EcoEducationEssence(
        id: '1',
        image: 'assets/images/huanbao1.png',
        title: '🌧️ The Raindrop Cycle: A Journey from Sky to Leaf',
        detail:
            'In the clouds above your head, a story quietly begins.Every raindrop starts as water vapor—rising from oceans, rivers, or the transpiration of plants.When it meets cold air high up, tiny water molecules cluster into ice crystals and droplets.Pushed by the wind, they stick to one another, growing heavy enough at last—to fall toward the earth.\n\nWhen the first raindrop hits the ground, it traps the dust floating in the air.The heat of the city, the fragrance of the forest, the "breath" of the soil—all are washed and purified in that single moment.Rain falling from the sky is not just a weather cycle;it is a ritual of ecological renewal.\n\nWhen raindrops land on leaves, they start a new journey.Some droplets slide off, merging into the ground and streams,while others are gently absorbed by leaf veins—that is the moment when plants "drink the rain."The tiny hairs and waxy layer on the leaf surface determine where the droplets go:some roll into beads, others seep into cells,helping plants store nutrients and water before drought arrives.\n\nThe world of plant roots also awakens to the sound of rain.Moisture seeps slowly through the gaps between soil particles,absorbed by the root hairs at the tips of fine roots,then transported to stems and leaves through the xylem,to take part in photosynthesis and nutrient transport.The hours after rain are a plant’s busiest "internal moment"—cell activity intensifies, stomata open to "breathe,"chlorophyll reactivates, and the air becomes fresher as a result.\n\nBut the raindrop’s journey is not over yet.When the sun shines again,some of the moisture evaporates back into the air,carrying the scent of flowers, earth, and vegetation,rising once more to return to the sky.This is nature’s cycle:from cloud to leaf, from leaf to soil, and from soil back to cloud.\n\nEvery raindrop completes a cycle of life’s flow.It washes away dust, nourishes plants, awakens the soil,and also reminds us—every breath of the earth is closely tied to this one rainfall.',
      ),
      EcoEducationEssence(
        id: '2',
        image: 'assets/images/huanbao2.png',
        title: '🌿 "The Breath of Leaves: The Secret Between Plants and Air"',
        detail:
            'After a rainfall, plants seem to take on new life. The air feels fresher, colors appear more vivid, and even the scent carried by the wind is tinged with the moist green of vegetation. In fact, all of this comes from the "breathing" that leaves are constantly performing.Leaves are like a plant’s lungs. On the surface of each seemingly smooth leaf, there are tens of thousands of tiny stomata hidden. These stomata open and close continuously, allowing the plant to take in carbon dioxide and release oxygen and water vapor. Through this gas exchange, plants complete photosynthesis—using sunlight to produce energy—and gift oxygen to the entire world. Half of the air humans breathe every day comes from these silent yet hardworking leaves.After rain, the air is humid, so leaves no longer need to worry about water loss through evaporation. Their stomata open wider, enabling plants to carry out photosynthesis more efficiently: absorbing more carbon dioxide and releasing more oxygen. Tiny raindrops also carry nitrogen and mineral particles, which provide additional nutrients to plants as they attach to leaves and evaporate. Thus, the vibrant green after rain is not an illusion, but a true "deep breath" of plants.Stomata are actually quite intelligent. During droughts, they close tightly to prevent leaves from drying out; when night falls or humidity rises, they open again. Different plants have developed distinct breathing methods based on their environments: tropical rainforest plants have large, numerous stomata to adapt to humid conditions; desert plants, on the other hand, hide their stomata on the undersides of leaves and even only "breathe" at night to conserve every drop of water.As plants breathe, they also reshape the air. Areas with dense vegetation have lower temperatures, higher humidity, and gentler air. This is a natural phenomenon called "plant transpiration cooling": when plants release water vapor, they take away heat, making the surrounding air cooler. For this reason, forests are not only the Earth’s oxygen factories but also natural "air conditioning systems."The breathing of plants and humans is a tacit exchange. We inhale oxygen and exhale carbon dioxide, while plants do exactly the opposite—inhaling carbon dioxide and releasing oxygen. Every deep breath we take is actually a sharing of the air’s gift with a leaf.\nSo, the next time you walk into a meadow or forest after rain, try pausing for a moment. Get close to a leaf and see if it still holds tiny water droplets, or if it glimmers slightly in the sunlight. That is the rhythm of a plant’s breath—the gentlest connection between life and air.',
      ),
      EcoEducationEssence(
        id: '3',
        image: 'assets/images/huanbao3.png',
        title: '🌱 "Soil Life After Rain"',
        detail:
            'The rain has stopped, yet the air still carries the scent of earth. It is a smell blending moisture, fresh grass, and microorganisms—what people call "the breath of soil." Behind this aroma, however, lies a massive wave of life activity.\nWhen raindrops hit the ground, they do not stay on the surface. Tiny droplets seep deep into the soil along the gaps around plant roots, awakening life that had been slumbering. Bacteria, fungi, nematodes, and earthworms that lay dormant during droughts start to stir. They become rapidly active in the moist soil, decomposing dead branches and fallen leaves, and converting organic matter into nutrients that plants can absorb. This is an invisible "regeneration ritual," led by microorganisms yet shaping the cycle of the entire ecosystem.\nThe 24 hours after rain are when soil life is most active. The number of microorganisms can multiply several times in an instant, oxygen consumption rises, and the carbon cycle is reactivated. At this moment, the soil is no longer an inert substance but a miniature city: fungal hyphae spread underground like a network, bacteria shuttle between mineral particles, and earthworms turn the soil layers in damp tunnels—allowing air and water to circulate within. Every grain of soil has its own ecological rhythm.\nPlant roots also sense new vitality at this time. Post-rain soil is soft and well-aerated, so roots can stretch more easily and absorb more water and nutrients. The sugars secreted by root tips even "feed" the surrounding microorganisms, which in turn protect the roots, break down minerals, and promote growth. Scientists call this phenomenon "rhizosphere symbiosis." Rain is precisely the signal that reinitiates this symbiotic relationship.\nMoreover, the changes we cannot see affect even larger systems. Moist soil can store more carbon dioxide, reducing greenhouse gases in the air; rain-moistened earth also prevents dust and erosion, maintaining ecological balance. Even a short light rain can reactivate the food chain and help the Earth "breathe" more smoothly.\nSoil is not silent—it is reawakened after every rainfall.When you bend down and see tiny bubbles rising from the ground, that may be the breath of microorganisms; when you catch that familiar earthy scent, it is millions of living beings responding to the sky.\nNext time you walk after rain, try squatting down to touch a handful of moist soil. It is not just the texture of the ground, but the starting point of life. Every raindrop reminds us: the world beneath our feet is also quietly growing.',
      ),
    ];
  }

  /// 根据ID查询环保教育内容
  /// [educationId] 教育内容ID
  /// 返回教育内容，不存在返回null
  EcoEducationEssence? queryEducationById(String educationId) {
    return _educationList.firstWhereOrNull(
      (education) => education.id == educationId,
    );
  }

  /// 添加新的环保教育内容
  /// [image] 图片路径
  /// [title] 标题
  /// [detail] 详情文字
  /// 返回创建的教育内容ID
  String appendEducation(String image, String title, String detail) {
    final newId = (_educationList.length + 1).toString();
    final newEducation = EcoEducationEssence(
      id: newId,
      image: image,
      title: title,
      detail: detail,
    );
    _educationList.add(newEducation);
    return newId;
  }

  /// 根据ID删除环保教育内容
  /// [educationId] 教育内容ID
  /// 返回是否删除成功
  bool removeEducationById(String educationId) {
    final index = _educationList.indexWhere((e) => e.id == educationId);
    if (index == -1) {
      return false; // 内容不存在
    }

    // 删除环保教育内容
    _educationList.removeAt(index);
    return true;
  }
}
